package com.breakfast.fun.ui.user.recharge.rechargemoney;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.breakfast.fun.Constant;
import com.breakfast.fun.R;
import com.breakfast.fun.base.BaseFragment;
import com.breakfast.fun.data.entity.user.User;
import com.breakfast.fun.data.entity.user.recharge.CmbPay;
import com.breakfast.fun.data.entity.user.recharge.PayBean;
import com.breakfast.fun.data.entity.user.recharge.PayResult;
import com.breakfast.fun.data.entity.user.recharge.RechargeMoney;
import com.breakfast.fun.data.entity.user.recharge.WeiPay;
import com.breakfast.fun.ui.user.UserFragment;
import com.breakfast.fun.ui.user.pay.BFPayActivity;
import com.breakfast.fun.ui.user.recharge.rechargerecord.RechargeRecordActivity;
import com.breakfast.fun.ui.web.CmbPayActivity;
import com.breakfast.fun.util.JumpUtil;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.PopUtil;
import com.breakfast.fun.util.SharedUtil;
import com.breakfast.fun.util.T;
import com.google.gson.Gson;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import butterknife.Bind;

/**
 * Created by Administrator on 2016/8/24.
 */
public class RechargeMoneyFragment extends BaseFragment<RechargeMoneyPresenter, RechargeMoneyModel> implements RechargeMoneyContract.View {
    @Bind(R.id.tv_recharge_money)
    TextView tvRechargeMoney;
    @Bind(R.id.et_recharge_money)
    EditText etRechargeMoney;
    @Bind(R.id.btn_next)
    Button btnNext;

    private static String payway = "cmbpay";
    public static Boolean isFromWeb = false;


    public static final int PLUGIN_NOT_INSTALLED = -1;
    public static final int PLUGIN_NEED_UPGRADE = 2;
    private final static String mode = "00";         //银联"00" 正式环境，"01"测试环境

    @Override
    public int getLayoutId() {
        return R.layout.fragment_recharge_money;
    }

    private String price;

    private PopupWindow popupWindow = null;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    String resultStatus = payResult.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {

                        T.show("充值成功!!");
                        showLoadingDialog(true);
                        presenter.getUser();

                    } else {
                        if (TextUtils.equals(resultStatus, "8000")) {
                            T.show("支付结果确认中");
                        } else if (TextUtils.equals(resultStatus, "4000")) {
                            T.show("支付失败,请检查是否已安装支付宝客户端");
                        } else {
                            T.show("支付失败");
                        }
                    }

                    break;
                }
                case SDK_CHECK_FLAG: {
                    T.show("检查结果为:" + msg.obj);
                    break;
                }
                default:
                    break;
            }
        }

    };

    @Override
    public void initView() {
        if (Constant.getUserData() == null) {
            T.show("请登录");
            JumpUtil.toLogin(context);
            return;
        }
        tvRechargeMoney.setText(Constant.getUserData().getMoney() + "");

        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (etRechargeMoney.getText().toString().trim().length() > 0) {
                    price = etRechargeMoney.getText().toString().trim();
                    double p = 0;
                    try {
                        p = Double.valueOf(price);
                        if (p < 1) {
                            T.show("最小充值1元,请重新输入!!");
                            return;
                        }
                    } catch (Exception e) {
                        T.show("请输入正确的充值金额!!");
                        return;
                    }

                    presenter.next(price);
                } else {
                    T.show("请输入充值金额！");
                }
            }
        });

    }

    @Override
    public void showPayWay(RechargeMoney rechargeMoney) {
        payway = "cmbpay";
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.widget_pop_pay, null);

        TextView tvRechargeSure = (TextView) contentView.findViewById(R.id.tv_recharge_sure);
        tvRechargeSure.setText(price + "元");

        Button btnRechargeSure = (Button) contentView.findViewById(R.id.btn_recharge_sure);

        btnRechargeSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                payForMoney(rechargeMoney.getData());
            }
        });

        RadioGroup rgPayWay = (RadioGroup) contentView.findViewById(R.id.user_recharge_rg_payway);
        rgPayWay.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup arg0, int checkid) {
                if (checkid == R.id.recharge_pay_rb_payway1) {
                    payway = "alipay";
                } else if (checkid == R.id.recharge_pay_rb_payway2) {
                    payway = "weipay";
                } else if (checkid == R.id.recharge_pay_rb_payway4) {
                    payway = "cmbpay";
                } else if (checkid == R.id.recharge_pay_rb_payway3) {
                    payway = "cuppay";
                }
            }
        });

        RadioButton rbAlipay = (RadioButton) contentView.findViewById(R.id.recharge_pay_rb_payway1);
        RadioButton rbWeipay = (RadioButton) contentView.findViewById(R.id.recharge_pay_rb_payway2);
        RadioButton rbCmbpay = (RadioButton) contentView.findViewById(R.id.recharge_pay_rb_payway4);
        RadioButton rbCuppay = (RadioButton) contentView.findViewById(R.id.recharge_pay_rb_payway3);

        popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        PopUtil.setPop(popupWindow);

        popupWindow.showAtLocation(getActivity().findViewById(R.id.fl_recharge), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        PopUtil popUtil = new PopUtil();
        popUtil.backgroundAlpha(getActivity(), 0.5f);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popUtil.backgroundAlpha(getActivity(), 1f);
            }
        });

        if (rechargeMoney.getData().getAlipay() == null) {
            rbAlipay.setVisibility(View.GONE);
        }
        if (rechargeMoney.getData().getWeiPay() == null) {
            rbWeipay.setVisibility(View.GONE);
        }
        if (rechargeMoney.getData().getCuppay() == null) {
            rbCuppay.setVisibility(View.GONE);
        }
        if (rechargeMoney.getData().getCmbpay() == null) {
            rbCmbpay.setVisibility(View.GONE);
        } else {
            if (rechargeMoney.getData().getCmbpay().getTip() != null &&
                    !TextUtils.isEmpty(rechargeMoney.getData().getCmbpay().getTip().trim())) {

                String tip = rechargeMoney.getData().getCmbpay().getTip();

                rbCmbpay.setText("招行一网通支付\n" + tip);
            }
        }


    }

    @Override
    public void refresh(User user) {
        hideLoadingDialog();
        if (user.getData().getMoney() == Constant.getUserData().getMoney()) {
            return;
        } else {
            SharedUtil.putString(context, "user", new Gson().toJson(user.getData()));
            Constant.setUserData(user.getData());
            UserFragment.isNeedRefesh = true;
            tvRechargeMoney.setText(user.getData().getMoney() + "");
            if (isFromWeb) {
                isFromWeb = false;
                return;
            }
            Intent intent = new Intent(getActivity(), RechargeRecordActivity.class);
            startActivity(intent);
        }
    }

    private void payForMoney(PayBean paybean) {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        switch (payway) {
            case "alipay":
                payForAli(paybean.getAlipay());
                break;
            case "weipay":
                payForWei(paybean.getWeiPay());
                break;
            case "cmbpay":
                payForCmb(paybean.getCmbpay());
                break;
            case "cuppay":
                if (!TextUtils.isEmpty(paybean.getCuppay().getTn().trim())) {
                    payForCup(paybean.getCuppay().getTn());
                } else {
                    T.show("获取订单流水号失败");
                }
            default:
                break;
        }
    }

    private void payForCup(String tn) {
        int ret = UPPayAssistEx.startPay(context, null, null, tn, mode);
        if (ret == PLUGIN_NEED_UPGRADE || ret == PLUGIN_NOT_INSTALLED) {
            // 需要重新安装控件
            L.e(" plugin not found or need upgrade!!!");
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("提示");
            builder.setMessage("完成购买需要安装银联支付控件，是否安装？");

            builder.setNegativeButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            UPPayAssistEx.installUPPayPlugin(context);
                            dialog.dismiss();
                        }
                    });

            builder.setPositiveButton("取消",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create().show();

        }
        L.e("" + ret);
    }

    private void payForWei(WeiPay pay) {
        final IWXAPI msgApi = WXAPIFactory.createWXAPI(context, null);
        msgApi.registerApp(Constant.WX_ID);

        PayReq payReq = new PayReq();
        payReq.appId = pay.getAppId();
        payReq.partnerId = pay.getPartnerId();
        payReq.prepayId = pay.getPrepayId();
        payReq.packageValue = "Sign=WXPay";
        payReq.nonceStr = pay.getNonceStr();
        payReq.timeStamp = pay.getTimeStamp();
        payReq.sign = pay.getSign();

        if (!msgApi.isWXAppInstalled()) {
            T.show("您还未安装微信,无法完成支付。");
            return;
        }

        msgApi.sendReq(payReq);
    }

    private void payForAli(String aliPay) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask payTask = new PayTask(RechargeMoneyFragment.this.getActivity());
                // 调用支付接口，获取支付结果
                String result = payTask.pay(aliPay);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public void payForCmb(CmbPay cmbPay) {
        Intent intent = new Intent(getActivity(), CmbPayActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("cmbpay", cmbPay);

        intent.putExtras(bundle);
        startActivity(intent);
    }


    @Override
    public void onResume() {
        super.onResume();

        showLoadingDialog(true);
        presenter.getUser();
    }
}
